package com.ibpd.henuocms.web.controller.manage;

import java.io.File;
import java.io.IOException;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import net.sf.json.JSONArray;

import org.apache.commons.fileupload.FileItem;
import org.apache.commons.fileupload.FileUploadException;
import org.apache.commons.fileupload.disk.DiskFileItemFactory;
import org.apache.commons.fileupload.servlet.ServletFileUpload;
import org.apache.commons.lang.StringUtils;
import org.jsoup.helper.StringUtil;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;

import com.ibpd.common.PageCommon;
import com.ibpd.henuocms.common.IbpdLogger;
import com.ibpd.henuocms.common.TxtUtil;
import com.ibpd.henuocms.exception.IbpdException;
import com.ibpd.henuocms.test.CusEntity;
import com.ibpd.henuocms.test.SQLDBUtil;

@Controller
public class Crm extends BaseController {
	@RequestMapping("manage/crm/getBaseBarCode.do")
	public String getBaseBarCode(Long modelId) throws IOException{
		PageCommon.printStringToConsole("modelId="+modelId);
		return "manage/crm/getBaseBarCode";
	}	
	@RequestMapping("manage/crm/index.do")
	public String index(Long modelId) throws IOException{
		PageCommon.printStringToConsole("modelId="+modelId);
		return "manage/crm/index";
	}
	@RequestMapping("manage/crm/distPrice.do")
	public String dictPrice() throws IOException{
		return "manage/crm/distPrice";
	}
	public static void main(String[] s) throws Exception{
		String suppCode="150025	150069	150045	150008	150018	150018	150025	150045	150018	150036	150045	150025	150018	150069	150025	150036	150045	150035	150045	150045	150036	150025	150018	150025	150018	010001	010070	030054	030150	040047	040029	010070	190007	190010	100003	100017	070020	070034	100002	100015	070027	030188	030190	030150	010064	010065	030188	030186	030150	030149	030188	030223	030223	030150	030186	030190	030149	030188	030050	030149	030188	030243	030150	030050	030149	030188	030190	030243	010225	030150	030149	030186	030188	030067	030003	030243	030223	010225	030135	030266	030050";
		String[] codes=suppCode.split("\t");
		String rtn="";
		SQLDBUtil.initConnection();
		for(String code:codes){
			
			rtn+=code+","+SQLDBUtil.getContraceNumber(code,"")+"\n";
		}
		SQLDBUtil.closeConnection();
		TxtUtil.writeTxtFile(rtn, new File("d:\\11.csv"));
		IbpdLogger.getLogger(Crm.class).info(rtn);
		
	}
	@RequestMapping("manage/crm/getDistPrice.do")
	public void getDistPrice(HttpServletResponse resp,org.springframework.ui.Model model,String goodsCode) throws IOException{
		//select * from [000].tbDistPrice where GoodsCode = '120000357' or GoodsCode='120000358'
		goodsCode=(goodsCode==null)?"":goodsCode;
		if(StringUtils.isBlank(goodsCode)){
			super.printMsg(resp, "-1", "", "goodsCode为空");
			return;
		}
		String[] ids=goodsCode.split("\t");
		String sql="";
		for(String id:ids){
			if(StringUtil.isBlank(id)){
				continue;
			}
			sql+="goodsCode='"+id+"' or ";
		}
		if(StringUtil.isBlank(sql)){
			super.printMsg(resp, "-2", "", "参数不正确");
			return;
		}
		sql="select * from [000].tbDistPrice where "+sql.substring(0,sql.length()-4);
		IbpdLogger.getLogger(this.getClass()).info(sql);
		List<Map<String,String>> rtn=SQLDBUtil.getDistPrice(sql);
		if(rtn.size()==0){
			super.printMsg(resp, "-3", "", "没有数据");
			return;
		}
		JSONArray json=JSONArray.fromObject(rtn);
		super.printJsonData(resp, json.toString());
	}
	@RequestMapping("manage/crm/doUploadByBaseBarCode.do")
	public void doUploadByBaseBarCode(HttpServletRequest request,HttpServletResponse response,org.springframework.ui.Model model,String uCode,String statistiscs,String split) throws IOException{
	
		DiskFileItemFactory factory = new DiskFileItemFactory();
		// 设置内存缓冲区，超过后写入临时文件
		factory.setSizeThreshold(10240000);
		// 设置临时文件存储位置
		String basePath = request.getRealPath("/")+"crm"+File.separatorChar;
			File file = new File(basePath);
			if(!file.exists())
				file.mkdirs();
			factory.setRepository(file);
			ServletFileUpload upload = new ServletFileUpload(factory);
			// 设置单个文件的最大上传值
			upload.setFileSizeMax(2097512);
			// 设置整个request的最大值
			upload.setSizeMax(3097512);
			upload.setHeaderEncoding("UTF-8");
			
			try {
				List<?> items = upload.parseRequest(request);
				FileItem item = null;
				String fileName = null;
				SQLDBUtil.initConnection();
				for (int i = 0 ;i < items.size(); i++){
					item = (FileItem) items.get(i);
					fileName = basePath + getDate()+"_"+request.getSession().getId()+"_getBaseBarCode.txt";
					if (!item.isFormField() && item.getName().length() > 0) {
						item.write(new File(fileName));
						String s=TxtUtil.readTxtFile(fileName);
						String[] d=s.split("\n");
						StringBuffer sb=new StringBuffer();
						for(String g:d){
							sb.append(g.trim()+","+SQLDBUtil.getBaseBarCode(g.trim())+"\r\n");							
						}
						
						TxtUtil.writeTxtFile(sb.toString(), new File(basePath + getDate()+"_"+request.getSession().getId()+"_getBaseCodeBar_new.txt"));
						model.addAttribute("file",new File(request.getContextPath()+"/crm/" + getDate()+"_"+request.getSession().getId()+"_getBaseCodeBar_new.txt"));
						response.getWriter().append(request.getContextPath()+"/crm/" + getDate()+"_"+request.getSession().getId()+"_getBaseCodeBar_new.txt");
						response.getWriter().flush();
					}
				}
				SQLDBUtil.closeConnection();
				//获取供应商合同号的sql：连接到192.105.128.1/erp5
//				SELECT top(1) ContractNumber,SupplierCode,EndDate FROM [jjlzb].[000].[tbContract] where ContractState=1 and SupplierCode=120054 order by EndDate desc
			} catch (FileUploadException e) {
				e.printStackTrace();
			} catch (Exception e) {
				e.printStackTrace();
			}
			
		}
	@RequestMapping("manage/crm/doUpload.do")
	public void doUpload(HttpServletRequest request,HttpServletResponse response,org.springframework.ui.Model model,String statistiscs,String split,String remark) throws IOException{
	
		DiskFileItemFactory factory = new DiskFileItemFactory();
		// 设置内存缓冲区，超过后写入临时文件
		factory.setSizeThreshold(10240000);
		// 设置临时文件存储位置
		String basePath = request.getRealPath("/")+"crm"+File.separatorChar;
			File file = new File(basePath);
			if(!file.exists())
				file.mkdirs();
			factory.setRepository(file);
			ServletFileUpload upload = new ServletFileUpload(factory);
			// 设置单个文件的最大上传值
			upload.setFileSizeMax(2097512);
			// 设置整个request的最大值
			upload.setSizeMax(3097512);
			upload.setHeaderEncoding("UTF-8");
			
			try {
				List<?> items = upload.parseRequest(request);
				FileItem item = null;
				String fileName = null;
				for (int i = 0 ;i < items.size(); i++){
					item = (FileItem) items.get(i);
					fileName = basePath + getDate()+"_"+request.getSession().getId()+".txt";
					if (!item.isFormField() && item.getName().length() > 0) {
						item.write(new File(fileName));
						List<CusEntity> cusList=processData(fileName,Boolean.parseBoolean(statistiscs),remark);
						StringBuffer content=new StringBuffer();
						for(CusEntity cus:cusList){
							String ss=cus.get合同号()+"\t"+cus.get供应商编码()+"\t"+cus.get部门编码()+"\t"+cus.get商品编码()+"\t"+cus.get调前价()+"\t"+cus.get调后价()+"\t"+cus.get数量()+"\t"+cus.get起始日()+"\t"+cus.get结束日()+"\t"+cus.get备注();
							if(split!=null && split.trim().equals("1")){
								ss=ss.replace("\t", ",");
							}
							IbpdLogger.getLogger(this.getClass()).info(ss);
							content.append(ss+"\n");
						}
						TxtUtil.writeTxtFile(content.toString(), new File(basePath + getDate()+"_"+request.getSession().getId()+"_new.txt"));
						model.addAttribute("file",new File(request.getContextPath()+"/crm/" + getDate()+"_"+request.getSession().getId()+"_new.txt"));
						response.getWriter().append(request.getContextPath()+"/crm/" + getDate()+"_"+request.getSession().getId()+"_new.txt");
						response.getWriter().flush();
					}
				}
				//获取供应商合同号的sql：连接到192.105.128.1/erp5
//				SELECT top(1) ContractNumber,SupplierCode,EndDate FROM [jjlzb].[000].[tbContract] where ContractState=1 and SupplierCode=120054 order by EndDate desc
			} catch (FileUploadException e) {
				e.printStackTrace();
			} catch (Exception e) {
				e.printStackTrace();
			}
			
		}
	private List<CusEntity> processData(String fName,Boolean statistiscs,String remark) throws IbpdException{
		
		SQLDBUtil.initConnection();
		Map<String,String> contractNo=new HashMap<String,String>();
		String[] unitCode=new String[]{};
		String[] allUnitCode=new String[]{"0002","0003","0004","0006","0009","0010","0013","0014","0015","0016","0017","0018","0020","0023","0025","0027","0029","0032","0033","0034","0035","0040","0041","0044","0046","0047","0048","0050","0051","0053","0055","0057","0059"};
//		if(uCode==null || uCode.trim().toUpperCase().equals("ALL")){
//			unitCode=new String[]{"0002","0003","0004","0006","0009","0010","0013","0014","0015","0016","0017","0018","0020","0023","0024","0025","0027","0029","0032","0033","0034","0035","0040","0041","0044","0046","0047","0048","0050","0051","0053","0054","0055","0057","0058","0059"};
//		}else{
//			unitCode=uCode.split(",");
//		}
		String s=TxtUtil.readTxtFile(fName);
		String[] d=s.split("\n");
		List<CusEntity> cusList=new ArrayList<CusEntity>();
		for(String line:d){
			IbpdLogger.getLogger(this.getClass()).info(line);
			String[] f=line.split("\t");
			Integer goodsCount=Integer.parseInt(f[4].trim());
			Integer loopCount=goodsCount;//应该循环多少次，往多少单位下分配退补商品数量
			Integer singleUnitGoodsCount=1;
			Integer rem=0;//余数
			if(f[f.length-1].toUpperCase().equals("ALL")){
				unitCode=allUnitCode;
			}else{
				unitCode=f[f.length-1].split(",");
			}
			if(unitCode.length>=goodsCount){
				loopCount=goodsCount;
			}else{
				loopCount=unitCode.length;//如果商品数量大于单位数量，那么 就得分配为每个单位 分配多少个商品
				if(goodsCount%unitCode.length==0){
					singleUnitGoodsCount=goodsCount/unitCode.length;
				}else{
					singleUnitGoodsCount=goodsCount/unitCode.length;
					rem=goodsCount%unitCode.length;//余数
					//把取到的余数做处理，分配给其他 门店
				}
				
			}
			for(Integer i=0;i<loopCount;i++){
				String uc=unitCode[i];
				String contractNumber=contractNo.get(f[0].trim());
				if(contractNumber==null || contractNumber.equals("")){
					contractNumber=SQLDBUtil.getContraceNumber(f[0].trim(),f[1].trim());
					if(contractNumber==null || StringUtils.isBlank(contractNumber)){
//						throw new IbpdException("没找到供应商编码为:"+f[0].trim()+"的合同信息");
						contractNo.put(f[0].trim(), "无此合同对照信息,编码:"+f[0].trim()+",部门:"+uc);
					}
					contractNo.put(f[0].trim(), contractNumber);
				}
				Integer cnt=singleUnitGoodsCount;
				if(rem!=0){
					if(i<rem){
						cnt++;
					}
				}
				cusList.add(new CusEntity(f[1].trim(),contractNumber,f[2].trim(),f[3].trim(),uc,cnt.toString(),getDate(),getDate(),/*getWeek().toString()*/remark,f[0].trim()));
			}
			if(statistiscs){
				cusList.add(new CusEntity("","","","","",goodsCount.toString(),"","","", ""));
			}
		}
		SQLDBUtil.closeConnection();
		return cusList;
	}
//	public static void main(String[] args){
//		List<String> weeks=new ArrayList<String>();
//		weeks.add("星期一");
//		weeks.add("星期二");
//		weeks.add("星期三");
//		weeks.add("星期四");
//		weeks.add("星期五");
//		weeks.add("星期六");
//		weeks.add("星期日");
//		Date date=new Date();
//		   SimpleDateFormat dateFm = new SimpleDateFormat("EEEE");
//		   String s=dateFm.format(date);
//		   System.out.println(weeks.indexOf(s)+1);
//	}
	private Integer getWeek(){
		List<String> weeks=new ArrayList<String>();
		weeks.add("星期一");
		weeks.add("星期二");
		weeks.add("星期三");
		weeks.add("星期四");
		weeks.add("星期五");
		weeks.add("星期六");
		weeks.add("星期日");
		Date date=new Date();
		   SimpleDateFormat dateFm = new SimpleDateFormat("EEEE");
		   String s=dateFm.format(date);
		   IbpdLogger.getLogger(this.getClass()).info(weeks.indexOf(s)+1);
		   return weeks.indexOf(s)+1;
	}
	private String getDate(){
		 java.util.Calendar c=java.util.Calendar.getInstance();    
	     java.text.SimpleDateFormat f=new java.text.SimpleDateFormat("yyyyMMdd");    
	     return f.format(c.getTime());   
	}
}
